<script>
import { Application } from '@splinetool/runtime'
import { getAreaDetail } from '@/services/car'
import { getBuildingInfo } from '@/services/park'
import { getParkInfo } from '@/services/park'
import DetailModal from '@/components/DetailModal.vue'
import * as echarts from 'echarts'
let spline
export default {
  name: 'HomeIndex',
  components: { DetailModal },
  data() {
    return {
      loading: true,
      targetDetail: {},
      targetType: '',
      visible: false,
      partData: {},
      pieOption: {},
      barOption: {},
      publicPath: import.meta.env.BASE_URL,
      mousePostion: {},
      scaleRatio: 1,
      width: 1920,
      height: 1080
    }
  },
  async mounted() {
    window.addEventListener('mousedown', this.getPosition)
    await this.initData()
    if (this.$refs.canvas) {
      setTimeout(() => {
        spline = new Application(this.$refs.canvas)
        spline?.load(`//localhost:5174/scene.splinecode`).then(() => {
          this.loading = false
          spline.addEventListener('mouseDown', (e) => {
            if (e.target.name.indexOf('停车场') < 0) {
              getBuildingInfo(e.target.id).then((res) => {
                this.targetDetail = res
                this.targetType = 'building'
                this.visible = true
              })
            } else {
              getAreaDetail(e.target.id).then((res) => {
                this.targetDetail = res
                this.targetType = 'area'
                this.visible = true
              })
            }
          })
        })
        const box = document.getElementsByClassName('screen-wrapper')[0]
        const scale = box.style.transform
        const scaleRatio = scale.match(/scale\((\S*),/)[1]
        this.scaleRatio = scaleRatio
        this.width = box.clientWidth * scaleRatio
        this.height = box.clientHeight * scaleRatio
      }, 800)
    }
  },
  methods: {
    async initData() {
      const {
        parkIncome: { xMonth, yIncome },
        parkIndustry,
        base
      } = await getParkInfo()
      this.partData = base
      this.pieOption = {
        color: ['#00B2FF', '#2CF2FF', '#892CFF', '#FF624D', '#FFCF54', '#86ECA2'],
        legend: {
          itemGap: 20,
          bottom: '0',
          icon: 'rect',
          itemHeight: 10, // 图例icon高度
          itemWidth: 10, // 图例icon宽度
          textStyle: {
            color: '#c6d1db'
          }
        },
        tooltip: {
          trigger: 'item'
        },
        series: [
          {
            name: '园区产业分析',
            type: 'pie',
            radius: ['55%', '60%'], // 设置内圈与外圈的半径使其呈现为环形
            center: ['50%', '40%'], // 圆心位置， 用于调整整个图的位置
            tooltip: {
              trigger: 'item',
              formatter: (params) => {
                return `${params.seriesName}</br><div style='display:flex;justify-content: space-between;'><div>${params.marker}${params.name}</div><div>${params.percent}%</div></div>`
              }
            },
            label: {
              show: false,
              position: 'center'
            },
            data: parkIndustry
          }
        ]
      }
      this.barOption = {
        tooltip: {
          trigger: 'axis',
          axisPointer: {
            type: 'shadow'
          }
        },
        grid: {
          // 让图表占满容器
          top: '10px',
          left: '0px',
          right: '0px',
          bottom: '0px',
          containLabel: true
        },
        xAxis: [
          {
            type: 'category',
            axisTick: {
              alignWithLabel: true,
              show: false
            },
            data: xMonth
          }
        ],
        yAxis: [
          {
            type: 'value',
            splitLine: {
              show: false
            }
          }
        ],
        series: [
          {
            name: '园区年度收入',
            type: 'bar',
            barWidth: '10px',
            data: yIncome.map((item, index) => {
              const color =
                index % 2 === 0
                  ? new echarts.graphic.LinearGradient(0, 0, 0, 1, [
                      { offset: 0.23, color: '#74c0f8' },
                      { offset: 1, color: 'rgba(116,192,248,0.00)' }
                    ])
                  : new echarts.graphic.LinearGradient(0, 0, 0, 1, [
                      { offset: 0.23, color: '#ff7152' },
                      { offset: 1, color: 'rgba(255,113,82,0.00)' }
                    ])
              return { value: item, itemStyle: { color } }
            })
          }
        ],
        textStyle: {
          color: '#B4C0CC'
        }
      }
      this.initChart()
    },
    initChart() {
      const myPieChart = echarts.init(this.$refs.pieChart)
      const myBarChart = echarts.init(this.$refs.barChart)
      myPieChart.setOption(this.pieOption)
      myBarChart.setOption(this.barOption)
      window.addEventListener('resize', function () {
        myPieChart.resize()
        myBarChart.resize()
      })
    },

    getPosition(e) {
      if (this.$refs.detailModal?.$refs?.target?.contains(e.target)) {
        return
      }
      let left =
        e.clientX -
        (document.body.clientWidth -
          document.getElementsByClassName('screen-wrapper')[0].clientWidth * this.scaleRatio) /
          2
      let top = e.clientY

      console.log(left, top)

      if (left + 300 > this.width) {
        left = this.width - 300
      }
      if (top + 200 > this.height) {
        top = this.height - 200
      }

      console.log(left, top)
      this.mousePostion = { left: left / this.scaleRatio, top: top / this.scaleRatio }
    }
  },

  onUnmounted() {
    spline?.dispose()
    window.removeEventListener('mousedown', this.getPosition)
  }
}
</script>
<template>
  <div class="model-container">
    <div v-if="loading" class="loading" ref="loading">
      <p class="text">园区资源加载中…</p>
      <div class="loading-process">
        <div class="process-wrapper"></div>
      </div>
    </div>
    <canvas ref="canvas" class="canvas"></canvas>
    <div class="all-charts" ref="homeContainer">
      <!-- 图表1 -->
      <div class="section-one">
        <img
          class="img-header"
          src="https://yjy-teach-oss.oss-cn-beijing.aliyuncs.com/smartPark/%E5%A4%A7%E5%B1%8F%E5%88%87%E5%9B%BE/%E5%9B%AD%E5%8C%BA%E6%A6%82%E5%86%B5%402x.png"
          alt=""
        />
        <div class="icons-container">
          <div class="item">
            <div class="icons-item building-icon">
              <span class="number">
                {{ partData?.buildingTotal }}
              </span>
            </div>
            <span class="title">楼宇总数</span>
            <span class="unity">（栋）</span>
          </div>
          <div class="item">
            <div class="icons-item enterprise-icon">
              <span class="number">
                {{ partData?.enterpriseTotal }}
              </span>
            </div>
            <span class="title">入驻企业总数</span>
            <span class="unity">（家）</span>
          </div>
          <div class="item">
            <div class="icons-item car-icon">
              <span class="number">
                {{ partData?.parkingTotal }}
              </span>
            </div>
            <span class="title">车位总数</span>
            <span class="unity">（个）</span>
          </div>
          <div class="item">
            <div class="icons-item rod-icon">
              <span class="number">
                {{ partData?.chargePoleTotal }}
              </span>
            </div>
            <span class="title">一体杆总数</span>
            <span class="unity">（个）</span>
          </div>
        </div>
      </div>
      <!-- 图表2 -->
      <div class="section-two">
        <img
          class="img-header"
          src="https://yjy-teach-oss.oss-cn-beijing.aliyuncs.com/smartPark/%E5%A4%A7%E5%B1%8F%E5%88%87%E5%9B%BE/%E5%9B%AD%E5%8C%BA%E5%B9%B4%E5%BA%A6%E6%94%B6%E5%85%A5%E5%88%86%E6%9E%90%402x.png"
          alt=""
        />
        <div class="bar-chart-titile">
          <span>单位：元</span>
          <div>
            <span class="bar-icon blue-bar-icon"></span>
            <span class="bar-icon red-bar-icon"></span>
            收入情况
          </div>
        </div>
        <div class="bar-chart" ref="barChart"></div>
      </div>
      <!-- 图表3 -->
      <div class="section-three">
        <img
          class="img-header"
          src="https://yjy-teach-oss.oss-cn-beijing.aliyuncs.com/smartPark/%E5%A4%A7%E5%B1%8F%E5%88%87%E5%9B%BE/%E5%9B%AD%E5%8C%BA%E4%BA%A7%E4%B8%9A%E5%88%86%E5%B8%83%402x.png"
          alt=""
        />
        <div class="pie-chart" ref="pieChart"></div>
      </div>
    </div>
    <detail-modal
      ref="detailModal"
      :visible="visible"
      :targetDetail="targetDetail"
      :targetType="targetType"
      :mousePostion="mousePostion"
      @updateVisible="(val) => (visible = val)"
    />
  </div>
</template>

<style scoped lang="scss">
.model-container {
  position: relative;
  height: 100%;
  background-color: black;
  width: 100%;
  flex-shrink: 0;
}
.loading {
  position: absolute;
  left: 66%;
  top: 40%;
  transform: translateX(-50%);
  text-align: center;
  .text {
    font-size: 14px;
    color: #909399;
    margin-bottom: 16px;
  }
  .loading-process {
    width: 280px;
    height: 4px;
    background: rgba(255, 255, 255, 0.16);
    border-radius: 20px;
    overflow: hidden;
  }
  .process-wrapper {
    height: 100%;
    width: 5%;
    background: linear-gradient(90deg, #48ffff 0%, #3656ff 100%);
    animation-duration: 1000s;
    animation-name: loading;
  }
  @keyframes loading {
    0% {
      transform: scaleX(1);
    }
    1% {
      transform: scaleX(38);
    }
    100% {
      transform: scaleX(40);
    }
  }
}
.all-charts {
  position: absolute;
  top: 0;
  left: 0;
  width: 480px;
  height: 100%;
  padding: 88px 20px 0;
  display: flex;
  flex-direction: column;
  background: linear-gradient(
    to left,
    rgba(0, 6, 15, 0) 0%,
    rgba(0, 6, 15, 0) 20%,
    rgba(0, 0, 0, 0.4) 30%,
    rgba(0, 0, 0, 0.6) 40%,
    rgba(1, 4, 11, 1) 70%,
    #04070d 100%
  );
  .img-header {
    height: 30px;
  }
}
.section-one {
  // flex-basis: 25%;
  height: 270px;
  .icons-container {
    display: flex;
    justify-content: space-between;
    padding: 20px 0;
    .item {
      text-align: center;
      display: flex;
      flex-direction: column;
      flex: 1;
      .icons-item {
        height: 80px;
        position: relative;
        .number {
          position: absolute;
          left: 50%;
          transform: translateX(-50%);
          font-size: 18px;
          font-family: FontquanXinYiGuanHeiTi, FontquanXinYiGuanHeiTi-Regular;
          color: #ffffff;
        }
      }
      .building-icon {
        background: url('@/assets/building-icon.png') no-repeat 50% 0 / contain;
      }
      .enterprise-icon {
        background: url('@/assets/enterprise-icon.png') no-repeat 50% 0 / contain;
      }
      .rod-icon {
        background: url('@/assets/rod-icon.png') no-repeat 50% 0 / contain;
      }
      .car-icon {
        background: url('@/assets/car-icon.png') no-repeat 50% 0 / contain;
      }
      .title,
      .unity {
        font-size: 14px;
        color: #cdd7e1;
      }
      .title {
        margin-top: 8px;
      }
    }
  }
}
.section-two {
  height: 330px;
  .bar-chart {
    width: 100%;
    height: calc(100% - 90px);
  }
}
.section-three {
  // flex-basis: 40%;
  height: 365px;
  .pie-chart {
    position: relative;
    margin: 0 auto;
    padding-bottom: 20px;
    width: 80%;
    height: calc(100% - 40px);
  }
}
.bar-chart-titile {
  display: flex;
  margin-top: 20px;
  justify-content: space-between;
  font-size: 14px;
  color: #c6d1db;
  .bar-icon {
    display: inline-block;
    width: 12px;
    height: 4px;
    vertical-align: middle;
  }
  .blue-bar-icon {
    background: linear-gradient(to right, #74c0f8, rgba(116, 192, 248, 0));
  }
  .red-bar-icon {
    background: linear-gradient(to right, #ff7152, rgba(255, 113, 82, 0));
  }
}
</style>
